package com.belf.common.utils;

import com.belf.common.utils.spring.SpringUtils;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Cache工具类
 *
 * @author belf
 */
public class CacheUtils
{
    private static Logger logger = LoggerFactory.getLogger(CacheUtils.class);

    private static CacheManager cacheManager = SpringUtils.getBean(CacheManager.class);

    //数据词典 永久存留
    public static final String SYS_CACHE = "sys-cache";
    //验证码用完直接del
    public static final String SYS_CAPTCHA = "sys-captcha";
    //token 根据application配置超时时间
    public static final String SYS_TOKEN = "sys-token";
    //请求url排重 存留10秒
    public static final String SYS_REPEAT_URL = "sys-repeat_url";
    //系统参数 永久存留
    public static final String SYS_CONFIG = "sys-config";
    //保障组全量传输方向 A>B 或 B>A
    public static final String SYS_GROUP_BTOA = "sys-belf-group-btoa";
    //自定义缓存
    public static final String SYS_CUSTOM = "sys-custom";

    /**
     * 获取SYS_CACHE缓存
     *
     * @param key
     * @return
     */
    public static Object get(String key)
    {
        return get(SYS_CACHE, key);
    }

    /**
     * 获取SYS_CACHE缓存
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public static Object get(String key, Object defaultValue)
    {
        Object value = get(key);
        return value != null ? value : defaultValue;
    }

    /**
     * 写入SYS_CACHE缓存
     *
     * @param key
     * @return
     */
    public static void put(String key, Object value)
    {
        put(SYS_CACHE, key, value);
    }

    /**
     * 从SYS_CACHE缓存中移除
     *
     * @param key
     * @return
     */
    public static void remove(String key)
    {
        remove(SYS_CACHE, key);
    }

    /**
     * 获取缓存
     *
     * @param cacheName
     * @param key
     * @return
     */
    public static Object get(String cacheName, String key)
    {
        Element element = getCache(cacheName).get(getKey(key));

        if(element == null){
            return null;
        }
        return element.getObjectValue();
    }

    /**
     * 获取缓存
     *
     * @param cacheName
     * @param key
     * @param defaultValue
     * @return
     */
    public static Object get(String cacheName, String key, Object defaultValue)
    {
        Object value = get(cacheName, getKey(key));
        return value != null ? value : defaultValue;
    }

    /**
     * 写入缓存
     *
     * @param cacheName
     * @param key
     * @param value
     */
    public static void put(String cacheName, String key, Object value)
    {
        Element element = new Element(key,value,1);
        getCache(cacheName).put(element);
    }

    /**
     * 设置有效期
     * @param cacheName
     * @param key
     * @param value
     * @param timeout 秒
     */
    public static void put(String cacheName, String key, Object value,int timeout)
    {
        Element element = new Element(key,value,timeout,timeout);
        getCache(cacheName).put(element);
    }

    /**
     * 从缓存中移除
     *
     * @param cacheName
     * @param key
     */
    public static void remove(String cacheName, String key)
    {
        getCache(cacheName).remove(getKey(key));
    }

    /**
     * 从缓存中移除所有
     *
     * @param cacheName
     */
    public static void removeAll(String cacheName)
    {
        Cache cache = getCache(cacheName);
        List<String> keys = cache.getKeys();
        if(keys != null && keys.size()>0){
            for(String item : keys){
                cache.remove(item);
            }
        }
        logger.debug("清理缓存： {} => {}", cacheName, keys);
    }

    /**
     * 从缓存中移除指定key
     *
     * @param keys
     */
    public static void removeByKeys(Set<String> keys)
    {
        removeByKeys(SYS_CACHE, keys);
    }

    /**
     * 从缓存中移除指定key
     *
     * @param cacheName
     * @param keys
     */
    public static void removeByKeys(String cacheName, Set<String> keys)
    {
        for (Iterator<String> it = keys.iterator(); it.hasNext();)
        {
            remove(it.next());
        }
        logger.info("清理缓存： {} => {}", cacheName, keys);
    }

    /**
     * 获取缓存键名
     *
     * @param key
     * @return
     */
    private static String getKey(String key)
    {
        return key;
    }

    /**
     * 获得一个Cache，没有则显示日志。
     *
     * @param cacheName
     * @return
     */
    public static Cache getCache(String cacheName)
    {
        Cache cache = cacheManager.getCache(cacheName);
        if (cache == null)
        {
            throw new RuntimeException("当前系统中没有定义“" + cacheName + "”这个缓存。");
        }
        return cache;
    }

    /**
     * 获取所有缓存
     *
     * @return 缓存组
     */
    public static String[] getCacheNames()
    {
//        return ((CacheManager) cacheManager).getCacheManager().getCacheNames();
//        String[] cacheNames =
        return cacheManager.getCacheNames();
    }

    /**
     * 获取一个cache分类下，所有的key
     * @param cacheName
     * @return
     */
    public static List<String> getKeys(String cacheName){
        return cacheManager.getCache(cacheName).getKeys();
    }
}
